﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Security.Cryptography;
using System.Xml;
using System.IO.Ports;
using System.Net.Sockets;
using System.Net;
using System.Threading;

namespace GCard
{
    public partial class TcpForm : Form
    {
        public TcpForm()
        {
            InitializeComponent();
        }

        Socket socketListen,//监听端口
               socketSever,//服务器端口
               socketClient;//客户端接口
        Thread threadListen;//监听线程
        Thread threadAcceptServer, threadAcceptClient;//服务器与客户端接收线程
        Thread threadClient; //客户端线程
        private void btn_startListen_Click(object sender, EventArgs e)
        {
            //if (threadListen != null || threadAcceptServer!=null)
            //{
            //    threadListen.Abort();
            //    threadAcceptServer.Abort();
            //}
            threadListen = new Thread(new ThreadStart(() =>
            {
                try
                {
                    //1、创建负责监听的socket
                    //第一个参数IP版本，第二个参数Socket类型，第三个参数使用的协议
                    socketListen = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                    //2、获取当前服务器IP地址
                    IPAddress ip = IPAddress.Parse(txt_tcpip.Text);
                    //3、获取当前应用程序端口号
                    IPEndPoint port = new IPEndPoint(ip, Int32.Parse(txt_tcpPort.Text));
                    //4、服务器开启对当前应用程序监听
                    socketListen.Bind(port);
                    //5、设置监听队列
                    socketListen.Listen(10);
                    //this.lbState.Items.Add("监听成功，等待客户端连接！");
                        this.BeginInvoke(new Action(() => { this.lbState.Items.Add("监听成功，等待客户端连接！"); }));this.BeginInvoke(new Action(() => { this.lbState.Items.Add("监听成功，等待客户端连接！"); }));
                    //6、接收客户端的连接
                    socketSever = socketListen.Accept();//注意：不停等待客户端连接，会让窗口死掉。Telent服务器与客户端：允许将电脑作为客户端服务器
                    //this.lbState.Items.Add(socketSever.RemoteEndPoint.ToString() + "连接成功！");
                    this.BeginInvoke(new Action(() => { this.lbState.Items.Add(this.lbState.Items.Add(socketSever.RemoteEndPoint.ToString() + "连接成功！")); }));
                }
                catch (Exception ex)
                {
                    MessageBox.Show("未查询到连接!" + ex.Message);
                }
            }));
            threadListen.IsBackground = true;
            threadListen.Start();

            threadAcceptServer = new Thread(() =>
            {
                while (true)
                {
                    if (socketSever != null)
                    {
                        try
                        {
                            NetworkStream netStream = new NetworkStream(socketSever);
                            byte[] dataSize = new byte[4];
                            netStream.Read(dataSize, 0, 4);
                            int size = System.BitConverter.ToInt32(dataSize, 0);
                            byte[] message = new byte[size];
                            int dataleft = size;
                            int start = 0;
                            while (dataleft > 0)
                            {
                                int recv = netStream.Read(message, start, dataleft);
                                start += recv;
                                dataleft -= recv;
                            }
                            //this.rtb_accept.Rtf = Encoding.Unicode.GetString(message);
                            this.BeginInvoke(new Action(() => { this.rtb_accept.Rtf = Encoding.Unicode.GetString(message); }));
                        }
                        catch
                        {
                            this.BeginInvoke(new Action(() => { lbState.Items.Add("断开连接..."); }));
                            //lbState.Items.Add("断开连接...");
                            break;
                        }
                    }
                }
                    
            });
            threadAcceptServer.IsBackground = true;
            threadAcceptServer.Start();
        }

        private void btn_severSendData_Click(object sender, EventArgs e)
        {
            string str = this.rtb_send.Rtf;
            int i = str.Length;
            if (i == 0)
            {
                return;
            }
            else
            {
                i *= 2;
            }
            byte[] dataSize = new byte[4];
            dataSize = System.BitConverter.GetBytes(i);
            byte[] sendData = System.Text.Encoding.Unicode.GetBytes(str);

            try
            {
                NetworkStream netStream = new NetworkStream(socketSever);
                netStream.Write(dataSize, 0, 4);
                netStream.Write(sendData, 0, sendData.Length);
                netStream.Flush();
                this.rtb_send.Rtf = "";
            }
            catch(Exception ex)
            {
                MessageBox.Show("无法发送！" + ex.Message);
            }
        }

        private void btn_closeLisence_Click(object sender, EventArgs e)
        {
            try
            {
                socketListen.Shutdown(SocketShutdown.Both);
                socketListen.Close();
                if (socketSever.Connected)
                {
                    socketSever.Close();
                    threadListen.Abort();
                    threadAcceptServer.Abort();
                }
            }
            catch
            {
                MessageBox.Show("监听尚未开始，关闭无效！");
            }
        }

        private void btn_requestConnect_Click(object sender, EventArgs e)
        {
            if (threadAcceptClient != null)
            {
                threadAcceptClient.Abort();
            }
            IPAddress ip = IPAddress.Parse(txt_tcpip1.Text);
            IPEndPoint port = new IPEndPoint(ip, Int32.Parse(txt_tcpPort1.Text));//服务器port
            socketClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            try
            {
                socketClient.Connect(port);
            }
            catch (Exception ex)
            {
                MessageBox.Show("连接服务器失败！" + ex.Message);
            }
            //this.btn_requestConnect.Enabled = false;
            threadAcceptClient = new Thread(() =>
            {
                while (true)
                {
                    try
                    {
                        NetworkStream netStream = new NetworkStream(socketClient);
                        byte[] dataSize = new byte[4];
                        netStream.Read(dataSize, 0, 4);
                        int size = System.BitConverter.ToInt32(dataSize, 0);
                        byte[] message = new byte[size];
                        int dataleft = size;
                        int start = 0;
                        while (dataleft > 0)
                        {
                            int recv = netStream.Read(message, start, dataleft);
                            start += recv;
                            dataleft -= recv;
                        }
                        this.BeginInvoke(new Action(() => { this.rtb_accept1.Rtf = Encoding.Unicode.GetString(message); }));
                        //this.rtb_accept1.Rtf = Encoding.Unicode.GetString(message);
                    }
                    catch
                    {
                        this.BeginInvoke(new Action(() => { this.lbState.Items.Add(lbState.Items.Add("断开连接...")); }));
                        //lbState.Items.Add("断开连接...");
                        break;
                    }
                }
            });
            threadAcceptClient.IsBackground = true;
            threadAcceptClient.Start();
        }

        private void btn_clientSendData_Click(object sender, EventArgs e)
        {
            string str = this.rtb_send1.Rtf;
            int i = str.Length;
            if (i == 0)
            {
                return;
            }
            else
            {
                i *= 2;
            }
            byte[] dataSize = new byte[4];
            dataSize = System.BitConverter.GetBytes(i);
            byte[] sendData = System.Text.Encoding.Unicode.GetBytes(str);

            try
            {
                NetworkStream netStream = new NetworkStream(socketClient);
                netStream.Write(dataSize, 0, 4);
                netStream.Write(sendData, 0, sendData.Length);
                netStream.Flush();
                this.rtb_send1.Rtf = "";
            }
            catch (Exception ex)
            {
                MessageBox.Show("无法发送！" + ex.Message);
            }
        }

        private void btn_closeConnect_Click(object sender, EventArgs e)
        {

        }






    }
}
